package cn.net.yugu.doraemon.netty.processor;

import cn.net.yugu.doraemon.netty.factory.biz.Biz;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @description:
 * @author: wanghongli
 * @create: 2022-07-12 14:08:01
 */
@Slf4j
public class MessageProcessor implements Runnable {
    private long submitTime = 0;
    private long beginTime = 0;
    private long endTime = 0;
    private boolean executeSuccess = true;

    public ChannelHandlerContext channelHandlerContext;
    public Object message;
    public Biz biz;
    public Map<String, Object> attributes;
    public MessageProcessorNotice processorNotice;

    public MessageProcessor() {
        submitTime = System.currentTimeMillis();
    }

    @Override
    public void run() {
        before();
        try {
            if (processorNotice != null) {
                if (!processorNotice.processMessageBefore(message, submitTime, beginTime)) {
                    return;
                }
            }
            biz.doBiz(channelHandlerContext, attributes, message);
        } catch (Throwable e) {
            executeSuccess = false;
            log.error("MessageProcessor execute error", e);
            e.printStackTrace();

            try {
                if (processorNotice != null) {
                    processorNotice.errorNotice(biz.getClass().getSimpleName() + "处理失败");
                }
            } catch (Exception ex) {
                log.error("errorPushMessage error", ex);
                e.printStackTrace();
            }

        } finally {
            after();
        }
    }

    protected void before() {
        beginTime = System.currentTimeMillis();
        if(log.isInfoEnabled()) {
            log.info("biz {} begin, wait: {}ms", biz, beginTime - submitTime);
        }
    }

    protected void after() {
        endTime = System.currentTimeMillis();
        if(log.isInfoEnabled()) {
            log.info("biz {} {} end, wait: {}ms, run:{}ms", biz, executeSuccess ? "success" : "fail", beginTime - submitTime, endTime - beginTime);
        }
    }
}
